<%@ Page Language="C#" MasterPageFile="~/Site.master" Title="Events Example" %>
<asp:Content ID="Content1" ContentPlaceHolderID="MainContent" Runat="Server">
    <h3>Customer Information</h3>
    <table>
        <tr>
            <td style="text-align:left">
                <AjaxData:GridView 
                    ID="GridView1" runat="server" CssClass="DataWebControlStyle" 
                    CellSpacing="0" CellPadding="3" DataKeyName="ID" 
                    SortColumn="Company" SortOrderAscendingImageUrl="~/Images/up.gif" SortOrderDescendingImageUrl="~/Images/dn.gif" 
                    EditCommandEvent="onEditCommand" 
                    DeleteCommandEvent="onDeleteCommand" 
                    UpdateCommandEvent="onUpdateCommand" 
                    CancelCommandEvent="onCancelCommand"
                    SortCommandEvent="onSortCommand"
                    DataBoundEvent="onDataBound">
                   <AlternatingRowStyle CssClass="AlternatingRowStyle" />
                   <RowStyle CssClass="RowStyle"/>
                   <HeaderStyle CssClass="HeaderStyle"/>
                   <Columns>
                        <AjaxData:GridViewCommandColumn ShowEditButton="true" ShowDeleteButton="true" ShowCancelButton="true" HeaderStyle-Wrap="false" ItemStyle-Wrap="false"/>
                        <AjaxData:GridViewBoundColumn HeaderText="Customer" DataField="Company" SortField="Company" HeaderStyle-HorizontalAlign="Left" ItemStyle-HorizontalAlign="Left"/>
                        <AjaxData:GridViewBoundColumn HeaderText="Contact" DataField="ContactName" SortField="ContactName" HeaderStyle-HorizontalAlign="Left" ItemStyle-HorizontalAlign="Left" HeaderStyle-Wrap="false" ItemStyle-Wrap="false"/>
                        <AjaxData:GridViewBoundColumn HeaderText="Title" DataField="ContactTitle" SortField="ContactTitle" HeaderStyle-HorizontalAlign="Left" ItemStyle-HorizontalAlign="Left" HeaderStyle-Wrap="false" ItemStyle-Wrap="false"/>
                   </Columns>
                </AjaxData:GridView>
            </td>
        </tr>
        <tr>
            <td style="text-align:right">
                <AjaxData:Pager ID="Pager1" runat="server" CssClass="PagerRowStyle" CurrentPageStyle-CssClass="PagerCurrentPage" OtherPageStyle-CssClass="PagerOtherPage" PageChangedEvent="pageChanged"></AjaxData:Pager>
            </td>
        </tr>
    </table>
    <br />
    <div id="divEvents" class="trace"></div>
    <script type="text/javascript">

        var _gridView;
        var _pager;

        var _customers;

        function pageLoad(sender, e)
        {
            writeMessage('Event pageLoad fired.');
            _gridView = GridView1;
            _pager = Pager1;
            loadCustomers();
        }

        function loadCustomers()
        {
            // We need to convert the sortorder which the WS understands.
            var sortColumn = _gridView.get_sortColumn();
            var sortOrder = (_gridView.get_sortOrder() == AjaxDataControls.GridViewSortOrder.Descending) ? 'DESC' : 'ASC';
            var startIndex = (_pager.get_pageIndex() * _pager.get_pageSize());

            DataService.GetCustomerList(startIndex, _pager.get_pageSize(), sortColumn, sortOrder, onLoadSuccess);
        }

        function onLoadSuccess(result)
        {
            _customers = result.Rows;
            _pager.set_recordCount(result.Total);
            bindCustomers();
        }

        function bindCustomers()
        {
            _gridView.set_dataSource(_customers);
            _gridView.dataBind();
        }
        
        function onDataBound(sender, e)
        {
            writeMessage('Event onDataBound fired.');
        }

        function onSortCommand(sender, e)
        {
            writeMessage('Event onSortCommand fired.');
            _gridView.set_sortColumn(e.get_sortColumn())
            _gridView.set_sortOrder(e.get_sortOrder());
            _pager.set_pageIndex(0); // need to reset the current page as sorting is changed
            _gridView.set_editIndex(-1);
            loadCustomers();
        }

        function onEditCommand(sender, e)
        {
            writeMessage('Event onEditCommand fired.');
            _gridView.set_editIndex(e.get_row().get_rowIndex());
        }

        function onDeleteCommand(sender, e)
        {
            writeMessage('Event onDeleteCommand fired.');
            if (confirm('Are you sure you want to delete this customer?'))
            {
                var customerId = _gridView.get_dataKeys()[e.get_row().get_rowIndex()];

                DataService.DeleteCustomer(
                                            customerId,
                                            function(result)
                                            {
                                                if (result == true)
                                                {
                                                    _gridView.set_editIndex(-1);
                                                    loadCustomers();
                                                }
                                            }
                                          );
            }
        }

        function onUpdateCommand(sender, e)
        {
            writeMessage('Event onUpdateCommand fired.');
            var row = e.get_row();
            var customerId = _gridView.get_dataKeys()[e.get_row().get_rowIndex()];

            //Since we support drag and drop the column index may vary, so get the current index first.

            var customerColumnIndex = _gridView.getColumnIndexByHeaderText('Customer');
            var contactColumnIndex = _gridView.getColumnIndexByHeaderText('Contact');
            var titleColumnIndex = _gridView.getColumnIndexByHeaderText('Title');

            //container is the tr, the first childNodes represents all the cell of that tr
            //and the next childNodes points to the elements of that specified cell.
            //Since we only have the textbox in each cell the index 0 points to that
            //textbox.
            
            var txtCompany = row.get_container().childNodes[customerColumnIndex].childNodes[0];
            var txtContact = row.get_container().childNodes[contactColumnIndex].childNodes[0];
            var txtTitle = row.get_container().childNodes[titleColumnIndex].childNodes[0];

            var customer = e.get_row().get_dataItem();

            customer.Company = txtCompany.value.trim();
            customer.ContactName = txtContact.value.trim();
            customer.ContactTitle = txtTitle.value.trim();

            DataService.UpdateCustomer(
                                        customerId,
                                        customer.Company,
                                        customer.ContactName,
                                        customer.ContactTitle,
                                        function(result)
                                        {
                                            if (result == true)
                                            {
                                                _gridView.set_editIndex(-1);
                                            }
                                        }
                                      );
        }

        function onCancelCommand(sender, e)
        {
            writeMessage('Event onCancelCommand fired.');
            _gridView.set_editIndex(-1);
        }

        function pageChanged(sender, e)
        {
            writeMessage('Event pageChanged fired.');
            _pager.set_pageIndex(e.get_newPageIndex());
            _gridView.set_editIndex(-1);
            loadCustomers();
        }
        
        function writeMessage(message)
        {
            var oldMessages = $get('divEvents').innerHTML 
            $get('divEvents').innerHTML = message + " - " + Date() + "<br/>" + oldMessages;
        }

    </script>
</asp:Content>